package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.KnowlageDetailActivity;
import com.jp.knowledge.adapter.KnowlageItemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.KnowlageData;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/15.
 */

public class DailyKnowledgeDetailFragment extends Fragment implements CanRefreshLayout.OnRefreshListener, ResultSubscriber.OnResultListener, OnItemListerner {

	private View contentView;
	@ViewInject(R.id.permissionView)
	private LinearLayout remindView;
	@ViewInject(R.id.remind_img)
	private ImageView remindImg;
	@ViewInject(R.id.remind_text)
	private TextView remindText;
	@ViewInject(R.id.remind_btn)
	private TextView remindBtn;
	@ViewInject(R.id.refresh)
	private CanRefreshLayout refreshLayout;
	@ViewInject(R.id.can_content_view)
	private RecyclerView contentRv;

	private Context mContext;
	private DateFormat dateFormat;
	private Calendar calendar;
	private String navType;

	private List<KnowlageData.GroupListBean> groupListBeen;
	private KnowlageItemAdapter adapter;
	private String cachePath;
	private FileCacheManager cacheManager;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if(contentView == null){
			mContext = getContext();
			dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
			contentView = View.inflate(mContext, R.layout.fragment_knowledge_detail, null);
			cacheManager = new FileCacheManager();
			x.view().inject(this, contentView);
			refreshLayout.setRefreshEnabled(true);
			refreshLayout.setLoadMoreEnabled(false);
			refreshLayout.setOnRefreshListener(this);
			contentRv.setHasFixedSize(true);
			contentRv.setLayoutManager(new LinearLayoutManager(mContext));
			groupListBeen = new ArrayList<>();
			adapter = new KnowlageItemAdapter(mContext, groupListBeen, (JpApplication) getActivity().getApplication());
			adapter.setOnItemListener(this);
			contentRv.setAdapter(adapter);
			updateData();
		}
		return contentView;
	}

	private void setRemindView(){
		if(contentView == null)
			return;
		if(calendar == null || navType == null)
			refreshLayout.setVisibility(View.GONE);
		else
			refreshLayout.setVisibility(View.VISIBLE);
		if(refreshLayout.getVisibility() == View.GONE
				|| (refreshLayout.getVisibility() == View.VISIBLE && adapter.getItemCount() == 0)){
			remindView.setVisibility(View.VISIBLE);
			remindText.setText("暂无数据~");
			remindBtn.setVisibility(View.GONE);
		} else{
			remindView.setVisibility(View.GONE);
		}
	}

	public void updateData(){
		if(contentView == null || calendar == null || navType == null)
			return;
		setRemindView();
		cachePath = mContext.getCacheDir().getPath()
				+ "/daily_knowledge_detail_"
				+ navType + "_"
				+ dateFormat.format(this.calendar.getTime()) + ".dat";
		readCache();
	}

	public void updateData(Calendar calendar){
		if(calendar == null || isSameDay(this.calendar, calendar))
			return;
		this.calendar = calendar;
		if(contentView != null) {
			groupListBeen.clear();
			adapter.updataAdapter(groupListBeen);
		}
		updateData();
	}

	public void updateData(String navType){
		if(navType == null || navType.equals(this.navType))
			return;
		this.navType = navType;
		updateData();
	}

	public void updateData(Calendar calendar, String navType){
		if(calendar == null || isSameDay(this.calendar, calendar)
				|| navType == null || navType.equals(this.navType))
			return;
		if(contentView != null && !isSameDay(this.calendar, calendar)){
			groupListBeen.clear();
			adapter.updataAdapter(groupListBeen);
		}
		this.calendar = calendar;
		this.navType = navType;
		updateData();
	}

	private boolean isSameDay(Calendar calendar1, Calendar calendar2){
		if(calendar1 == null || calendar2 == null
				|| calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR)
				|| calendar1.get(Calendar.MONTH) != calendar2.get(Calendar.MONTH)
				|| calendar1.get(Calendar.DAY_OF_MONTH) != calendar2.get(Calendar.DAY_OF_MONTH))
			return false;
		return true;
	}

	private void readCache(){
		Observable.create(new Observable.OnSubscribe<List<KnowlageData.GroupListBean>>() {
			@Override
			public void call(Subscriber<? super List<KnowlageData.GroupListBean>> subscriber) {
				List<KnowlageData.GroupListBean> data = (List<KnowlageData.GroupListBean>) cacheManager.readObject(cachePath);
				subscriber.onNext(data);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<List<KnowlageData.GroupListBean>>() {
			@Override
			public void onCompleted() {
				if(adapter.getItemCount() > 0)
					onRefresh();
				else
					refreshLayout.autoRefresh();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(List<KnowlageData.GroupListBean> data) {
				groupListBeen.clear();
				if(data != null && data.size() > 0)
					groupListBeen.addAll(data);
				adapter.updataAdapter(groupListBeen);
				setRemindView();
			}
		});
	}

	private void saveCache(){
		if(cachePath == null)
			return;
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(groupListBeen, cachePath);
			}
		}).start();
	}

	@Override
	public void onRefresh() {
		if(calendar == null || navType == null){
			onCompleted(1);
			return;
		}
		JsonObject param = new JsonObject();
		param.addProperty("time", dateFormat.format(calendar.getTime()));
		param.addProperty("navType", navType);
		HttpHelper.getInstance(mContext).knowledgeList(param, 1, this);
	}

	@Override
	public void onStart(int requestType) {}
	@Override
	public void onCompleted(int requestType) {
		refreshLayout.refreshComplete();
	}
	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}
	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
		} else{
			groupListBeen.clear();
			List<KnowlageData> knowlageDatas = data.getList(KnowlageData.class);
			if(knowlageDatas != null && knowlageDatas.size() > 0){
				for(KnowlageData knowlageData : knowlageDatas){
					if(knowlageData == null || knowlageData.getGroupList() == null)
						continue;
					groupListBeen.addAll(knowlageData.getGroupList());
				}
			}
			adapter.updataAdapter(groupListBeen);
			setRemindView();
			saveCache();
		}
	}

	@Override
	public void onItemClick(View view, int position) {
		int type = groupListBeen.get(position).getPackageType();
		KnowlageData.GroupListBean data = groupListBeen.get(position);

		long startTime = data.getStartTime();
		long currentTimeMillis = System.currentTimeMillis();
		Calendar today = Calendar.getInstance();
		today.setTime(new Date(currentTimeMillis));
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date(startTime));

		UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
		int vip =  userData == null ? 0 : userData.getIsVip();
		if(currentTimeMillis < startTime && (vip != 1 || (!isSameDay(today, calendar)))){
			ToasUtil.toast(mContext, "未到开放时间，暂不能查看!");
			return;
		}
		if(data.getOnlyVip() == 1 && vip != 1){
			ToasUtil.toast(mContext, "本套餐只对VIP用户开放，请开通VIP!");
			return;
		}
		if(type == 26) {
			Intent intent = new Intent(mContext, KnowlageDetailActivity.class);
			intent.putExtra("id", groupListBeen.get(position).getMainId());
			intent.putExtra("packageId", groupListBeen.get(position).getPackageId());
			intent.putExtra("title", groupListBeen.get(position).getPackageTitle());
			startActivity(intent);
		} else {
			Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
			intent.putExtra("id", data.getPackageId());
			intent.putExtra("type", data.getPackageType());
			intent.putExtra("linkTitle", data.getPackageTitle());
			intent.putExtra("linkIcon", data.getPackageCover());
			startActivity(intent);
		}
	}
}
